package com.ly.ticket;

/**
 * 使用多线程模拟三个窗口同时售票100张
 */
public class SellTicket {
    public static void main(String[] args) {
//        //测试
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
//        //启动售票
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

        SellTicket02 sellTicket01 = new SellTicket02();
        SellTicket02 sellTicket02 = new SellTicket02();
        SellTicket02 sellTicket03 = new SellTicket02();
        new Thread(sellTicket01).start();
        new Thread(sellTicket02).start();
        new Thread(sellTicket03).start();

    }
}
//使用Thread方式
class SellTicket01 extends Thread{
    private  int ticketNum=100;//让多个线程共享num
    @Override
    public void run() {
        while (true){
            if (ticketNum<=0){
                System.out.println("票卖完了");
                break;
            }else {
                System.out.println(getName()+"卖出了第"+ticketNum--+"票，剩余："+ticketNum);
            }
            //休眠50ms,模拟网络延迟
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("线程名"+Thread.currentThread().getName()+"售出一张票"+"剩余票数="+(--ticketNum));
        }
    }
}
//使用接口方式
class SellTicket02 implements Runnable{
    private static int ticketNum=100;//让多个线程共享num
    @Override
    public void run() {
        while (true){
            if (ticketNum<=0){
                System.out.println("票卖完了");
                break;
            }else {
                System.out.println(Thread.currentThread().getName()+"卖出了第"+ticketNum--+"票，剩余："+ticketNum);
            }
            //休眠50ms,模拟网络延迟
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
